// news-system-modern/src/components/sandbox/SideMenu.tsx
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { Layout, Menu } from 'antd';
import { useLocation, useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
import './SideMenu.scss';
import {
  UserOutlined,
  HomeOutlined,
  TeamOutlined,
  SafetyCertificateOutlined,
  EditOutlined,
  AuditOutlined,
  GlobalOutlined,
  SettingOutlined,
  FileOutlined,
  AppstoreOutlined,
  UploadOutlined,
  CheckCircleOutlined,
  StopOutlined
} from '@ant-design/icons';
import { selectCollapsed } from '../../store/features/collapsedSlice';
import { selectUserRights } from '../../store/features/userSlice';
import auth from '../../utils/auth';
import { STORAGE_KEYS } from '../../constants/common';

const { Sider } = Layout;

// 定义菜单项接口
interface MenuItem {
  key: string;
  icon?: React.ReactNode;
  label: string;
  children?: MenuItem[];
  permission?: string;
}

// Ant Design菜单项类型
type AntMenuItem = {
  key: string;
  icon?: React.ReactNode;
  label: string;
  children?: AntMenuItem[];
};

// 定义静态菜单项
const staticMenuItems: MenuItem[] = [
  {
    key: '/home',
    icon: <HomeOutlined />,
    label: '首页',
    permission: '/home'
  },
  {
    key: '/user-profile',
    icon: <UserOutlined />,
    label: '个人中心',
    permission: '/user-profile'
  },
  {
    key: '/user-manage',
    icon: <TeamOutlined />,
    label: '用户管理',
    permission: '/user-manage',
    children: [
      {
        key: '/user-manage/list',
        label: '用户列表',
        permission: '/user-manage/list'
      }
    ]
  },
  {
    key: '/right-manage',
    icon: <SafetyCertificateOutlined />,
    label: '权限管理',
    permission: '/right-manage',
    children: [
      {
        key: '/right-manage/role/list',
        label: '角色列表',
        permission: '/right-manage/role/list'
      },
      {
        key: '/right-manage/right/list',
        label: '权限列表',
        permission: '/right-manage/right/list'
      }
    ]
  },
  {
    key: '/news-manage',
    icon: <EditOutlined />,
    label: '新闻管理',
    permission: '/news-manage',
    children: [
      {
        key: '/news-manage/add',
        label: '撰写新闻',
        icon: <EditOutlined />,
        permission: '/news-manage/add'
      },
      {
        key: '/news-manage/draft',
        label: '草稿箱',
        icon: <FileOutlined />,
        permission: '/news-manage/draft'
      },
      {
        key: '/news-manage/category',
        label: '新闻分类',
        icon: <AppstoreOutlined />,
        permission: '/news-manage/category'
      }
    ]
  },
  {
    key: '/audit-manage',
    icon: <AuditOutlined />,
    label: '审核管理',
    permission: '/audit-manage',
    children: [
      {
        key: '/audit-manage/audit',
        label: '审核新闻',
        permission: '/audit-manage/audit'
      },
      {
        key: '/audit-manage/list',
        label: '审核列表',
        permission: '/audit-manage/list'
      }
    ]
  },
  {
    key: '/publish-manage',
    icon: <GlobalOutlined />,
    label: '发布管理',
    permission: '/publish-manage',
    children: [
      {
        key: '/publish-manage/unpublished',
        label: '待发布',
        icon: <UploadOutlined />,
        permission: '/publish-manage/unpublished'
      },
      {
        key: '/publish-manage/published',
        label: '已发布',
        icon: <CheckCircleOutlined />,
        permission: '/publish-manage/published'
      },
      {
        key: '/publish-manage/sunset',
        label: '已下线',
        icon: <StopOutlined />,
        permission: '/publish-manage/sunset'
      }
    ]
  },
  {
    key: '/system/settings',
    icon: <SettingOutlined />,
    label: '系统设置',
    permission: '/system/settings'
  }
];

/**
 * 过滤菜单项
 * 根据用户权限过滤菜单项，只显示用户有权限访问的菜单
 * 
 * @param items 菜单项列表
 * @param checkPermissionFn 权限检查函数
 * @returns 过滤后的菜单项列表
 */
const filterMenuItems = (items: MenuItem[], checkPermissionFn: (path: string) => boolean): MenuItem[] => {
  return items.filter(item => {
    // 检查当前项权限
    const hasItemPermission = item.permission ? checkPermissionFn(item.permission) : true;
    
    if (!hasItemPermission) {
      return false;
    }
    
    // 如果有子项，递归过滤子项
    if (item.children && item.children.length > 0) {
      const filteredChildren = filterMenuItems([...item.children], checkPermissionFn);
      
      // 如果过滤后没有子项，检查父菜单是否应该显示
      if (filteredChildren.length === 0) {
        return item.permission && checkPermissionFn(item.permission);
      }
      
      // 返回包含过滤后子菜单的新对象
      item.children = filteredChildren;
      return true;
    }
    
    return true;
  });
};

/**
 * 转换菜单项为Ant Design菜单格式
 * 将自定义菜单项结构转换为Ant Design菜单组件所需的格式
 * 
 * @param items 自定义菜单项列表
 * @returns Ant Design菜单项列表
 */
const transformMenuItems = (items: MenuItem[]): AntMenuItem[] => {
  return items.map(item => {
    const menuItem: AntMenuItem = {
      key: item.key,
      icon: item.icon,
      label: item.label,
      children: item.children && item.children.length > 0
        ? transformMenuItems(item.children)
        : undefined
    };
    
    // 如果没有子菜单，则不设置children属性
    if (!menuItem.children) {
      delete menuItem.children;
    }
    
    return menuItem;
  });
};

/**
 * 侧边栏菜单组件
 * 根据用户权限动态生成菜单，支持折叠状态
 */
const SideMenu: React.FC = () => {
  const location = useLocation();
  const navigate = useNavigate(); // 使用useNavigate钩子进行导航
  
  // 从Redux获取折叠状态和权限列表
  const isCollapsed = useSelector(selectCollapsed);
  const reduxRights = useSelector(selectUserRights);
  
  // 保存菜单项和默认选中键
  const [menuItems, setMenuItems] = useState<AntMenuItem[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [openKeys, setOpenKeys] = useState<string[]>([]);
  // 添加一个状态来跟踪权限是否已更新
  const [rightsVersion, setRightsVersion] = useState<number>(0);

  // 添加监听localStorage变化的效果
  useEffect(() => {
    // 定义事件处理函数
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === STORAGE_KEYS.USER_RIGHTS) {
        console.log('权限已在localStorage中更新，重新生成菜单');
        setRightsVersion(prev => prev + 1); // 触发重新渲染
      }
    };
    
    // 添加事件监听器
    window.addEventListener('storage', handleStorageChange);
    
    // 清理函数
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  // 检查权限函数
  const checkPermission = useCallback((path: string): boolean => {
    // 从Redux获取权限
    if (reduxRights && reduxRights.length > 0) {
      return reduxRights.includes(path);
    }
    
    // 从localStorage获取权限 - 确保每次都读取最新的
    try {
      const rightsStr = localStorage.getItem(STORAGE_KEYS.USER_RIGHTS);
      if (rightsStr) {
        const rights = JSON.parse(rightsStr);
        return rights.includes(path);
      }
    } catch (error) {
      console.error('读取权限失败:', error);
    }
    
    // 使用auth工具获取权限
    return auth.hasPermission(path);
  }, [reduxRights, rightsVersion]); // 添加rightsVersion作为依赖项

  // 生成菜单项 - 使用useMemo优化性能
  const generateMenuItems = useMemo(() => {
    console.log('重新生成菜单项，权限版本:', rightsVersion);
    // 过滤菜单项
    const filteredItems = filterMenuItems([...staticMenuItems], checkPermission);
    
    // 转换为Ant Design菜单格式
    return transformMenuItems(filteredItems);
  }, [checkPermission, rightsVersion]); // 添加rightsVersion作为依赖项

  // 在组件挂载或权限变化时设置菜单项
  useEffect(() => {
    console.log('更新菜单项');
    setMenuItems(generateMenuItems);
  }, [generateMenuItems]);

  // 在路径变化时更新选中状态
  useEffect(() => {
    const { pathname } = location;
    setSelectedKeys([pathname]);
    
    // 展开当前选中项的父菜单
    if (!isCollapsed) {
      const patternPath = (path: string) => path.split('/').slice(0, 3).join('/');
      const parentKey = patternPath(pathname);
      
      if (pathname !== parentKey) {
        setOpenKeys([parentKey]);
      }
    }
  }, [location, isCollapsed]);

  // 点击菜单项的处理函数
  const handleMenuClick = (e: { key: string }) => {
    navigate(e.key);
  };

  // 处理子菜单展开/折叠
  const handleOpenChange = (keys: string[]) => {
    setOpenKeys(keys);
  };

  // 每当权限更新时手动触发菜单重新渲染
  useEffect(() => {
    const storedRights = auth.getUserRights();
    if (storedRights && storedRights.length > 0) {
      if (JSON.stringify(storedRights) !== JSON.stringify(reduxRights)) {
        console.log('权限已更新，触发菜单重新渲染');
        setRightsVersion(prev => prev + 1);
      }
    }
  }, [reduxRights]);

  return (
    <Sider
      trigger={null}
      collapsible
      collapsed={isCollapsed}
      width={200}
      style={{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
        top: 0,
        bottom: 0
      }}
    >
      <div className="logo-container">
        <h1>{isCollapsed ? '新闻' : '新闻发布管理系统'}</h1>
      </div>
      
      <Menu
        theme="dark"
        mode="inline"
        items={menuItems}
        selectedKeys={selectedKeys}
        openKeys={openKeys}
        onClick={handleMenuClick}
        onOpenChange={handleOpenChange}
        key={`menu-${rightsVersion}`} // 添加键来强制重新渲染
      />
    </Sider>
  );
};

export default SideMenu;